package com.luobu.javaee.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;

@Component
public class FileIO {

    /**
     * 读入TXT文件
     */
    public static String readFile(String pathname) throws IOException {
        String res = "";
        try (FileReader reader = new FileReader(pathname);
             BufferedReader br = new BufferedReader(reader) // 建立一个对象，它把文件内容转成计算机能读懂的语言
        ) {
            String line;
            while ((line = br.readLine()) != null) {
                res = res + line + "\n";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static void writeFile(String pathname, String content) {

        try {
            File writeName = new File(pathname);

            // 检查文件是否存在，如果存在则删除
            if (writeName.exists()) {
                writeName.delete();
            }

            // 创建新文件
            writeName.createNewFile();

            try (FileWriter writer = new FileWriter(writeName);
                 BufferedWriter out = new BufferedWriter(writer)) {
                out.write(content); // 将content写入文件
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readFileToString(File file) {
        StringBuilder content = new StringBuilder();

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            Scanner scanner = new Scanner(fileInputStream);

            while (scanner.hasNextLine()) {
                content.append(scanner.nextLine());
            }

            scanner.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return content.toString();
    }

    public static String readMultipartFileToString(MultipartFile file) {
        StringBuilder content = new StringBuilder();

        try {
            InputStream bb = file.getInputStream();
            InputStreamReader streamReader = new InputStreamReader(bb);
            BufferedReader reader = new BufferedReader(streamReader);
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            reader.close();
            bb.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return content.toString();
    }

    // 获取资源文件夹目录
    public static String getResourceDir(){
        String projDir = System.getProperty("user.dir");
        String filepath = projDir + File.separator + "src" + File.separator + "main" + File.separator
                + "resources" + File.separator + "static";
        return filepath;
    }

    public static String getFileArchivePath(Long userId, Long archiveId) throws IOException {
        String resourcePath = getResourceDir();
        String userIdString = String.format("%06d", userId); // 将userId格式化为六位的字符串
        String filePath = "";
        if(archiveId == -1) {
            filePath = resourcePath + File.separator + "document" + File.separator + userIdString
                    + File.separator + "default";
        }
        else {
            filePath = resourcePath + File.separator + "document" + File.separator + userIdString
                    + File.separator + String.format("%06d", archiveId);
        }
        return filePath;
    }

    public static String getPicArchivePath(Long userId, Long archiveId) throws IOException {
        String resourcePath = getResourceDir();
        String userIdString = String.format("%06d", userId); // 将userId格式化为六位的字符串
        String filePath = "";
        if(archiveId == -1) {
            filePath = resourcePath + File.separator + "picture" + File.separator + userIdString
                    + File.separator + "default";
        }
        else {
            filePath = resourcePath + File.separator + "picture" + File.separator + userIdString
                    + File.separator + String.format("%06d", archiveId);
        }
        return filePath;
    }

    public static String getFilePath(Long userId, String docName, Long archiveId) throws IOException {
        String filePath = getFileArchivePath(userId, archiveId);
        filePath = filePath + File.separator + docName;
        return filePath;
    }

    public static String getUserDocDir(Long userId) throws IOException {
        String resourcePath = getResourceDir();
        String userIdString = String.format("%06d", userId); // 将userId格式化为六位的字符串
        String userDocDir = resourcePath + File.separator + "document" + File.separator + userIdString;
        return userDocDir;
    }

    public static String getPictureDirPath(Long userId, String docName, Long archiveId) throws IOException {
        String picArchivePath = getPicArchivePath(userId, archiveId);
        String userIdString = String.format("%06d", userId); // 将userId格式化为六位的字符串
        String filePath = picArchivePath + File.separator + docName;
        return filePath;
    }

    public static void createDir(String filePath) {
        File file = new File(filePath);

        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
    }

    public static void createFile(String filePath) throws IOException {
        File file = new File(filePath);

        if (!file.exists()) {
            file.createNewFile();
        }
    }

    public static String getFolderPath(String folderPath) {
        int lastBackslashIndex = folderPath.lastIndexOf("\\");
        if (lastBackslashIndex != -1) {
            return folderPath.substring(0, lastBackslashIndex);
        }
        return "";
    }

    // 输入文件夹路径，检测文件夹是否已经被创建，未被创建则新建
    public static void resourceDirCheck(String folderPath) {
        File parentFolder = new File(folderPath);
        if (!parentFolder.exists()) {
            parentFolder.mkdirs();
        }

        String remainingPath = folderPath.substring(folderPath.indexOf("resources") + 10);
        String[] subfolders = remainingPath.split("/");
        File currentFolder = parentFolder;
        for (String subfolder : subfolders) {
            File subfolderFile = new File(currentFolder, subfolder);
            if (!subfolderFile.exists()) {
                subfolderFile.mkdir();
            }
            currentFolder = subfolderFile;
        }
    }

    // 输入文件路径，检测文件的父文件夹是否已经被创建，未被创建则新建
    public static void resourcePathCheck(String filePath) {
        resourceDirCheck(getFolderPath(filePath));
    }

    public static void moveFile(String sourceFilePath, String destinationFilePath) {
        File sourceFile = new File(sourceFilePath);
        File destinationFile = new File(destinationFilePath);

        try {
            Files.move(sourceFile.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
            // 处理文件移动异常
        }
    }

    public static void moveFolder(String sourceFolderPath, String destinationFolderPath) {
        File sourceFolder = new File(sourceFolderPath);
        File destinationFolder = new File(destinationFolderPath);

        try {
            Files.move(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件夹移动成功！");
        } catch (IOException e) {
            e.printStackTrace();
            // 处理文件夹移动异常
        }
    }

}



